// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html
let login = require("./Login.js");
var Utils = require("./Utils.js");
var interval;
const cmd = {
    MATCH_FIX_GAME_RANDOM_USER: 1,//匹配,指定游戏随机用户
    MATCH_FIX_GAME_RANDOM_USER_CANCEL: 3,//取消匹配,指定游戏随机用户
    GAME_AGAIN: 13,//再来一局
    GAME_AGAIN_OK: 16,//同意再来一局
    GAME_AGAIN_NO: 17, //不同意
    GO_AWAY: 8 //去匹配另外的人
}
let ROBEOT = 9;

const code = {
    MATCH_NOT_ENOUGH_AGAIN: 4008,
    MATCH_NOT_ENOUGH: 4006,
    OTHER_IS_CLICK: 5017,
}
const STATUS = {
    STATUS_NONE: -1,
    STATUS_NORMAL: 0,
    STATUS_WAIT_FRIEND: 1, //发起邀请，等对方接受
    STATUS_FRIEND_READY: 2, //对方准备好，等你进入游戏
    STATUS_FRIEND_RUN: 3, //对方逃跑
    STATUS_SELF_READY: 4, //接受邀请，准备进入游戏
}

cc.Class({
    extends: cc.Component,

    properties: {
        selfNode: {
            default: null,
            type: cc.Node
        },
        friendNode: {
            default: null,
            type: cc.Node
        },

        resultNode: {
            default: null,
            type: cc.Node
        },
        countLabel: cc.Label,

        scoreLabel: cc.Label,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        let frameSize = cc.director.getOpenGLView().getFrameSize();
        let rate = frameSize.height / frameSize.width;
        if(rate < 16 / 9){
            var canvas = this.node.getComponent(cc.Canvas);
            canvas.fitHeight = true;
            canvas.fitWidth = false;
            cc.log("fit height");
        }
    },

    start() {
        try {
            cc.log("showAd");
            jsb.reflection.callStaticMethod("RootViewController", "callNativeUIWithTitle:andContent:", "test", "Yes! you call a Native UI from Reflection");
        } catch (e) {
            cc.log("showAd exception:" + e.stack);
        }


        this.selfNodeScript = this.selfNode.getComponent("Self");
        this.selfNodeScript.init();
        this.friendNodeScript = this.friendNode.getComponent("Friend");
        this.friendNodeScript.init();
        this.startAgainButton = this.node.getChildByName("start_bt");
        this.changeMemberButton = this.node.getChildByName("change_member");


        this.matchNode = cc.director.getScene().getChildByName("match_node");
        if (!this.matchNode) {
            console.error("matchNode is null");
            return;
        }
        this.data = this.matchNode.getComponent("ResultData").getData();
        this.selfNodeScript.onMatchSuccess(this.data.selfInfo);
        this.friendNodeScript.onMatchSuccess(this.data.friendInfo);

        this.buttonStatus = STATUS.STATUS_NORMAL;
        this.getGameResult()
        // this.onPomeloListenerStart();

        this.waitToCreateRoomTime = 5;
        this.waitToCreateRoom = function () {
            cc.log("waitToCreateRoom");
            if (this.buttonStatus == STATUS.STATUS_FRIEND_READY) {
                this.waitToCreateRoomTime--;
                if (this.waitToCreateRoomTime >= 0) {
                    this.setStartBtLabelContent("对方已准备好," + this.waitToCreateRoomTime + "s后自动开战")
                }
                if (this.waitToCreateRoomTime == 0) {
                    this.createAndEnterGame(); //自动创建房间号
                }
            } else {
                cc.log("等待过程中状态发生了变化，this.buttonStatus =" + this.buttonStatus);
            }
        };
    },

    onDestroy() {
        console.log("游戏结果场景被销毁");
        pomelo.off("onVolkshalle");
        this.unscheduleAllCallbacks();
        clearTimeout(this.onWaitTimer);
    },

    getGameResult() {
        cc.log("getGameResult data =" + this.data);

        var todayTime = Math.floor(new Date().getTime() / 1000 / 60 / 60 / 24);
        var defeatNum = parseInt(cc.sys.localStorage.getItem(this.data.friendInfo.id + "_defeat_" + todayTime));
        if (!defeatNum) {
            defeatNum = 0;
        }
        var winNum = parseInt(cc.sys.localStorage.getItem(this.data.friendInfo.id + "_win_" + todayTime));
        if (!winNum) {
            winNum = 0;
        }

        if (this.data.defeat) {
            //失败
            Utils.resetFrame(this.resultNode.getComponent(cc.Sprite), "mzGameResource/image_fail");
            this.setStartBtLabelContent("不服，再来一局");
            defeatNum++;
        } else if (this.data.victory) {
            this.setStartBtLabelContent("别走，再来一局");
            Utils.resetFrame(this.resultNode.getComponent(cc.Sprite), "mzGameResource/image_success");
            winNum++;
        } else if (this.data.drawn) {
            this.setStartBtLabelContent("不服，再来一局");
            Utils.resetFrame(this.resultNode.getComponent(cc.Sprite), "mzGameResource/image_drawn");
            defeatNum++;
            winNum++;
        }
        this.countLabel.string = `今日对决${winNum + defeatNum}场`;
        this.scoreLabel.string = `${winNum}:${defeatNum}`;
        cc.sys.localStorage.setItem(this.data.friendInfo.id + "_win_" + todayTime, winNum);
        cc.sys.localStorage.setItem(this.data.friendInfo.id + "_defeat_" + todayTime, defeatNum);


        //过2秒自己溜
        if (this.data.friendInfo.type == ROBEOT) {
            setTimeout(() => {
                if( this.buttonStatus == STATUS.STATUS_NORMAL){
                    console.log("机器人对方已溜");
                    this.rebotResponse(cmd.GO_AWAY);
                }
            }, Math.floor((Math.random() * 5) + 3) * 1000);

            setTimeout(() => {
                if( this.buttonStatus == STATUS.STATUS_NORMAL){
                    if(Math.random() * 2 > 1){
                        console.log("机器人邀请再来一局");
                        this.rebotResponse(cmd.GAME_AGAIN);
                    }
                }
            }, Math.floor((Math.random() * 2) + 1) * 1000);
        }
    },

    friendIsGoAway() {
        if (!this.friendNodeScript) {
            return;
        }
        this.friendNodeScript.showTopTip("溜了溜了，江湖再见");
        // this.startButton.getComponent(cc.Button).interactable = false;
        // this.setStartBtLabelContent("对方已经逃跑啦");
        // this.startButton.opacity = 125;
        this.friendIsGone = true;
        this.changeStatus(STATUS.STATUS_FRIEND_RUN);
    },

    reMatch() {
        //重新找其他人匹配
        this.data.reMatch = true;
        this.matchNode.getComponent("ResultData").init(this.data);
        cc.director.loadScene("match");
    },


    setStartBtLabelContent(content) {
        this.startAgainButton.getChildByName("start_label").getComponent(cc.Label).string = content;
    },

    setChangeMemberLabelContent(content) {
        this.changeMemberButton.getChildByName("start_label").getComponent(cc.Label).string = content;
    },


    clickReMatch() {
        cc.log("clickReMatch status");
        try {
            if (this.playAgainTimer) {
                clearTimeout(this.playAgainTimer); //清除进入游戏倒计时
            }
            // this.sendMessageToFriend(cmd.GO_AWAY);
            this.reMatch();
            this.changeStatus(STATUS.STATUS_NONE);
        } catch (e) {
            cc.log(e.stack);
            cc.director.loadScene("match");
        } finally {

        }
    },

    createAndEnterGame(){
        this.data.defeat = false;
        this.data.victory = false;
        this.data.drawn = false;
        this.matchNode = cc.director.getScene().getChildByName("match_node");
        this.matchNode.getComponent("ResultData").init(this.data);
        cc.game.addPersistRootNode(this.matchNode);
        cc.log("first time to load addPersistRootNode data =" + this.data.toString());
        cc.director.loadScene("game");
    },

    playAgain() {
        if (STATUS.STATUS_FRIEND_READY == this.buttonStatus) {
            this.createAndEnterGame();
        } else{
            this.changeStatus(STATUS.STATUS_WAIT_FRIEND);
        }
        
        // setTimeout(() => {
        //     if (Math.random() * 2 > 1) {
        //         this.changeStatus(STATUS.STATUS_WAIT_FRIEN);
        //     } else {

        //     }
        // }, Math.floor((Math.random() * 3) + 1) * 1000);

    },


    onCloseClick() {
        cc.log("onCloseClick");
    },

    rebotResponse(type) {
        if (type === cmd.GAME_AGAIN) {
            console.log("rebot log4js--进入倒计时，5s后创建房间号");
            this.changeStatus(STATUS.STATUS_FRIEND_READY); //对方准备等你创建房间号
        } else if (type === cmd.GAME_AGAIN_OK) {
            //已近得到了房间号，直接进入游戏了，不墨迹
            // this.data.room = info.room;
            //todo 不可以按返回键退出
            //再次进入游戏
            this.matchNode.getComponent("ResultData").init(this.data);
            cc.director.loadScene("game");
            this.changeStatus(STATUS.STATUS_NONE)
        } else if (type === cmd.GAME_AGAIN_NO) {
            console.log("rebot log4js--，对方不同意再来一局，清除再来一局定时器----");
            this.friendIsGoAway();
            clearTimeout(this.playAgainTimer);
        } else if (type === cmd.GO_AWAY) {
            console.log("rebot log4js--，对方找另外的人匹配，显示对方溜了");
            this.friendIsGoAway();
        }
    },

    changeStatus(status) {
        cc.log("changeStatus status =" + status + " lastStatus =" + this.buttonStatus);
        if (this.buttonStatus == status) {
            cc.log("Status not change");
            return;
        }
        this.buttonStatus = status;
        switch (status) {
            case STATUS.STATUS_NORMAL:
                this.startAgainButton.getComponent(cc.Button).interactable = true;
                this.changeMemberButton.getComponent(cc.Button).interactable = true;
                break;
            case STATUS.STATUS_WAIT_FRIEND:
                this.startAgainButton.getComponent(cc.Button).interactable = false;
                this.changeMemberButton.getComponent(cc.Button).interactable = false;
                this.setStartBtLabelContent("等待对方应战");
                this.onWaitTimer = setTimeout(() => {
                    if (Math.random() * 2 > 1) {
                        //机器人答应迎战
                        cc.log("机器人答应迎战"); 
                        this.rebotResponse(cmd.GAME_AGAIN_OK);
                    } else {
                        this.rebotResponse(cmd.GO_AWAY);
                        cc.log("机器人逃跑");
                    }
                }, Math.random() * 3000 + 1000);

                break;
            case STATUS.STATUS_FRIEND_READY:
                this.startAgainButton.getComponent(cc.Button).interactable = true;
                this.changeMemberButton.getComponent(cc.Button).interactable = true;


                //todo 显示倒计时
                this.setStartBtLabelContent("对方已准备好," + this.waitToCreateRoomTime + "后自动开战")
                this.schedule(this.waitToCreateRoom, 1);

                break;
            case STATUS.STATUS_FRIEND_RUN:
                this.startAgainButton.getComponent(cc.Button).interactable = false;
                this.changeMemberButton.getComponent(cc.Button).interactable = true;
                this.setStartBtLabelContent("对方已经逃跑啦");
                this.unschedule(this.waitToCreateRoom);
                clearTimeout(this.onWaitTimer);
                break;
            case STATUS.STATUS_SELF_READY:
                this.startAgainButton.getComponent(cc.Button).interactable = false;
                this.changeMemberButton.getComponent(cc.Button).interactable = false;
                break;
            default:
                if (Utils.isAndroid()) {
                    // clearTimeout(this.onHideTimer);
                    clearTimeout(this.onWaitTimer);
                    this.unschedule(this.waitToCreateRoom);
                    mz.offHide(() => {
                        console.log("取消进入后台监听 timestamp");
                    })
                }
        }
    },



    goAwayToMain() {
        // this.sendMessageToFriend(cmd.GO_AWAY);
        cc.director.loadScene("mz_game_main");
    }
});



